<template>
  <view class="popup-wrap">
    <view class="title"> 排便记录 </view>
    <view class="time-wrap">
      <text class="name">排便时间</text>
      <view class="time" @tap="showTime(state.collectTime, props.poptype)">
        <text class="titles">{{ parseTime(state.collectTime, '{y}-{m}-{d} {h}:{i}') }}</text>
        <img
          class="img"
          src="https://ainengli.meilianshuke.com/jkhx/common/my-arrow-right.png"
          alt=""
        />
      </view>
    </view>
    <view
      class="select-wrap"
      v-for="item in selectForms"
      :key="item.label"
    >
      <view class="label">{{ item.label }}</view>
      <view class="value">{{ state[item.key] }}</view>
      <SingleSelect
        :options="item.options"
        v-model="state[item.key]"
        :activeStyle="{border: '4rpx solid #E5E6EB'}"
        :inactiveStyle="{border: '4rpx solid transparent'}"
        @change="(val) => onChange(item.key, val)"
        :itemWidth="item.width"
        :itemHeight="item.height"
        :borderWidth="item.borderWidth"
      />
    </view>
    <view class="fixedBtn1" @tap="sure">
      <text class="name">提交</text>
    </view>
    
    <view>
      <up-datetime-picker
        :show="timeShow"
        v-model="state.collectTime"
        :closeOnClickOverlay="true"
        :maxDate="new Date().getTime()"
        mode="datetime"
        @close="closeDateTime"
        @confirm="confirmDateTime"
        @cancel="closeDateTime"
        @change="changeDateTime"
      />
    </view>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from 'vue'
import { parseTime } from '@/utils/tools'
import store from '@/store'
import SingleSelect from '../../../components/MySingleSelect/index'
import { saveDefecate } from '@/module/src/api/defecate'
import type { IDefecateData } from '@/module/src/api/defecateModel'

const props = defineProps({
  poptype: {
    type: String,
    default: ''
  },
  defecateDetail: {
    type: Object,
    default: () => ({})
  },
  show: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['toggleOutPopup', 'onReset'])

const timeShow = ref(false)

const selectForms = reactive([
  {
    label: '排便颜色',
    key: 'colorCode',
    width: 48,
    height: 48,
    borderWidth: 8,
    options: [
      { type: 'color', color: '#E7E7E9', value: '灰白/粘土色', label: '灰白/粘土色' },
      { type: 'color', color: '#EDC43A', value: '浅黄', label: '浅黄' },
      { type: 'color', color: '#C4A16A', value: '黄褐/棕褐', label: '黄褐/棕褐' },
      { type: 'color', color: '#50392A', value: '深褐', label: '深褐' },
      { type: 'color', color: '#2E663F', value: '绿色', label: '绿色' },
      { type: 'color', color: '#242223', value: '黑色', label: '黑色' },
      { type: 'color', color: '#CF5556', value: '红色/暗红', label: '红色/暗红' }
    ]
  },
  {
    label: '排便形状',
    key: 'shapeCategory',
    width: 70,
    height: 70,
    borderWidth: 6,
    options: [
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape1.png', value: '硬块状', label: '硬块状' },
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape2.png', value: '香肠状但表面结块', label: '香肠状但表面结块' },
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape3.png', value: '香肠状有裂缝', label: '香肠状有裂缝' },
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape4.png', value: '香肠/蛇状光滑', label: '香肠/蛇状光滑' },
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape5.png', value: '软块边缘清晰(易断)', label: '软块边缘清晰(易断)' },
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape6.png', value: '松散碎块', label: '松散碎块' },
      { type: 'image', src: 'https://ainengli.meilianshuke.com/jkhx/common/shape7.png', value: '水样，无固体', label: '水样，无固体' }
    ]
  },
  {
    label: '排便感受',
    key: 'defecateFeel',
    width: 96,
    height: 96,
    borderWidth: 0,
    options: [
      {
        type: 'image',
        selectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/greate-active.png',
        unselectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/greate.png',
        value: '非常顺畅',
        label: '非常顺畅'
      },
      {
        type: 'image',
        selectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/good-active.png',
        unselectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/good.png',
        value: '轻微用力',
        label: '轻微用力'
      },
      {
        type: 'image',
        selectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/bad-active.png',
        unselectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/bad.png',
        value: '明显费力',
        label: '明显费力'
      },
      {
        type: 'image',
        selectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/difficult-active.png',
        unselectedSrc: 'https://ainengli.meilianshuke.com/jkhx/common/difficult.png',
        value: '排不干净',
        label: '排不干净'
      }
    ]
  }
])

function getDefaultState() {
  return {
    collectTime: new Date().getTime(),
    colorCode: '黄褐/棕褐',
    shapeCategory: '香肠/蛇状光滑',
    defecateFeel: '非常顺畅',
    userId: store.state.userInfo.userId,
    empi: store.state.userInfo.patientInfo.empi
  }
}
const state = reactive<IDefecateData>({ ...getDefaultState() })

watch(
  [() => props.show, () => props.defecateDetail],
  ([show, defecateDetail]) => {
    if (show) {
      if (defecateDetail && Object.keys(defecateDetail).length) {
        Object.assign(state, getDefaultState(), defecateDetail)
      } else {
        Object.assign(state, getDefaultState())
      }
    }
  },
  { immediate: true, deep: true }
)

// const valueLabelMap = computed(() => {
//   const map: Record<string, Record<string, string>> = {}
//   selectForms.forEach(form => {
//     map[form.key] = {}
//     form.options.forEach((opt: any) => {
//       map[form.key][opt.value] = opt.label
//     })
//   })
//   return map
// })

const sure = () => {
  const params = {
    ...state,
    collectTime: parseTime(state.collectTime, '{y}-{m}-{d} {h}:{i}:00')
  }
  uni.showLoading({
    title: '加载中'
  })
  saveDefecate(params).then((res) => {
    emit('toggleOutPopup', false)
    if (res.code === 0) {
      if (props.defecateDetail?.id) {
        uni.hideLoading()
        setTimeout(() => {          
          uni.showToast({
            title: '保存成功',
            duration: 2000
          })
        }, 0);
        emit('onReset')
      } else {
        uni.navigateTo({
          url: '/module/src/pages/healthPortrait/defecateAnalyze?id=' + res.data?.id
        })
      }
    }
  })
}

const showTime = (date: any, type: string) => {
  if (props.defecateDetail?.id) return
  timeShow.value = true
}

const closeDateTime = () => {
  timeShow.value = false
}

const confirmDateTime = () => {
  timeShow.value = false
}

const changeDateTime = (time: string) => {
  console.log('changeDateTime', time)
}

const onChange = (key: string, value: string) => {
  state[key] = value
}
</script>

<style lang="scss" scoped>
.popup-wrap {
  padding-bottom: calc(160rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(160rpx + env(safe-area-inset-bottom));
  .title {
    padding: 32rpx;
    font-size: 32rpx;
    font-weight: 700;
    text-align: center;
    border-bottom: 1rpx solid #e5e6eb;
  }

  .time-wrap {
    position: relative;
    display: flex;
    justify-content: space-between;
    padding: 32rpx;
    margin: 32rpx;
    background: #fafafa;
    border: 1rpx solid #e5e6eb;
    border-radius: 16rpx;

    .name {
      font-size: 30rpx;
      font-weight: 700;
      color: #222;
    }

    .time {
      min-width: 200rpx;
      font-size: 30rpx;
      font-weight: 400;
      color: #222;
      text-align: right;

      .titles {
        display: inline-block;
        vertical-align: middle;
      }

      .img {
        display: inline-block;
        width: 30rpx;
        height: 30rpx;
        vertical-align: middle;
      }
    }
  }

  .select-wrap {
    margin: 40rpx 32rpx 0;
    .label {
      font-size: 32rpx;
      color: #222222;
      font-weight: 600;
    }
    .value {
      font-size: 28rpx;
      color: #00D1B6;
      margin: 16rpx 0 8rpx;
    }
  }

  .fixedBtn1 {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    padding: 24rpx 0;
    padding-bottom: calc(24rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
    color: #fff;
    text-align: center;
    background: #fff;

    .name {
      display: inline-block;
      width: calc(100% - 60rpx);
      padding: 22rpx 0;
      margin: 0 30rpx;
      font-size: 32rpx;
      background: #00d1b6;
      border-radius: 50rpx;
    }
  }
}
</style>
